from models import *

from django.contrib import admin
from django.conf.urls.defaults import patterns
from django.http import Http404, HttpResponseRedirect

import re

move_regex = r'^(?P<obj_id>\d+)/move/(?P<direction>up|down)/?$'

class ReorderableAdmin(admin.ModelAdmin):

    def get_object(self, request, model, obj_pk):
        """Helper function that returns an object if it exists and if the user
           has change permission for it.
        """
        try:
            obj = model._default_manager.get(pk=obj_pk)
        except model.DoesNotExist:
            obj = None
        if not self.has_change_permission(request, obj):
            raise PermissionDenied
        if obj is None:
            raise Http404('%s object with primary key %r does not exist.' % (model.__name__, obj_pk))
        return obj

    def get_urls(self):
        urls = super(ReorderableAdmin, self).get_urls()
        my_urls = patterns('',
            (move_regex, self.move),
        )
        return my_urls + urls

    def __call__(self, request, url):
        # Django-1.0.x compatibility
        if url:
            m = re.match(move_regex, url)
            if m:
                return self.move(request, m.group('obj_id'), m.group('direction'))
        return super(ReorderableAdmin, self).__call__(request, url)

    def move(self, request, obj_id, direction):
        if not request.user.has_perm('%s.%s' % (self.model._meta.app_label,
                                                self.model._meta.get_change_permission())):
            raise Unauthorized

        obj = self.get_object(request, self.model, obj_id)
        if direction == 'up':
            obj.move_up()
        else:
            obj.move_down()

        return HttpResponseRedirect('../../../')

class CSSAdmin(ReorderableAdmin):
    list_display = ('path', 'media', 'condition', 'reorder')
    list_filter = ('sites',)
    fields = ('path', 'media', 'condition', 'sites')

class JSAdmin(ReorderableAdmin):
    list_display = ('path', 'condition', 'reorder')
    list_filter = ('sites',)
    fields = ('path', 'condition', 'sites')

admin.site.register(CSS, CSSAdmin)
admin.site.register(JS, JSAdmin)
